package com.daikuan.fffkuaiban.ui.fragment;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.daikuan.fffkuaiban.R;
import com.jarhead.common.base.BaseFragment;
import com.jarhead.common.commonutils.ToastHelper;
import com.daikuan.fffkuaiban.adapter.ExpandableListViewAdapter;
import com.daikuan.fffkuaiban.adapter.GridViewAdapter;
import com.daikuan.fffkuaiban.bmobBean.ListConfig;
import com.daikuan.fffkuaiban.bmobBean.RecListBean;
import com.daikuan.fffkuaiban.ui.activity.WebViewActivity;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;

/**
 * Created by jiming1 on 2017/7/1.
 */
public class SecondFragment extends BaseFragment {

	@Bind(R.id.expendablelistview)
	ExpandableListView expendablelistview;
	GridView gridView;
	@Bind(R.id.refresh)
	TwinklingRefreshLayout refreshLayout;
	List<ListConfig> groups;
	List<List<ListConfig>> childs;
	Set<String> listId;
	@Bind(R.id.llNetErro)
	LinearLayout llNetErro;
	@Override
	protected int getLayoutResource() {
		return R.layout.fragment_second;
	}

	@Override
	public void initPresenter() {

	}

	@Override
	public void setInitialSavedState(SavedState state) {
		super.setInitialSavedState(state);
	}

	@Override
	public void setRetainInstance(boolean retain) {
		super.setRetainInstance(retain);
	}

	@Override
	protected void initView() {

		SinaRefreshView headerView = new SinaRefreshView(getActivity());
		headerView.setArrowResource(R.mipmap.arrow);
		headerView.setTextColor(0xff745D5C);
		refreshLayout.setHeaderView(headerView);
		refreshLayout.setEnableLoadmore(false);

		refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
			@Override
			public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
				initData();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						refreshLayout.finishRefreshing();
					}
				}, 2000);
			}

		});

		View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_header, null);
		gridView = (GridView) view.findViewById(R.id.gridView);
		expendablelistview.addHeaderView(view);

		expendablelistview.setGroupIndicator(null);

		expendablelistview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
				ListConfig listConfig = childs.get(i).get(i1);
				WebViewActivity.skip(getActivity(), listConfig.channel_gourl, listConfig.channel_name);
				return false;
			}
		});

		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				GridViewAdapter adapter = (GridViewAdapter) adapterView.getAdapter();
				RecListBean recListBean = adapter.getItem(i);
				WebViewActivity.skip(getActivity(), recListBean.hot_gourl, recListBean.hot_name);
			}
		});
	}

	@Override
	protected void initData() {
		llNetErro.setVisibility(View.GONE);
		expendablelistview.setVisibility(View.VISIBLE);
		getRectList();
		getList();
	}

	private void getList() {

		BmobQuery query = new BmobQuery("list_config");
		query.order("createdAt");
		query.order("list_id");
		query.findObjectsByTable(new QueryListener<JSONArray>() {
			@Override
			public void done(JSONArray jsonArray, BmobException e) {
				try {
					if (e == null) {
						List<ListConfig> listConfigs = JSON.parseArray(jsonArray.toString(), ListConfig.class);
						formatList(listConfigs);
						ExpandableListViewAdapter adapter = new ExpandableListViewAdapter(groups, childs, getActivity());
						expendablelistview.setAdapter(adapter);

						for (int i = 0; i < groups.size(); i++) {
							expendablelistview.expandGroup(i);
						}
						expendablelistview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
							@Override
							public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
								return true;
							}
						});

					} else {
						showNetErro();
					}
				} catch (Exception e2) {
					Log.e("XXX", "初始化列表失败");
					showNetErro();
				}
			}
		});

	}

	public void getRectList() {
		BmobQuery type_info = new BmobQuery("rec_list");
		type_info.order("createdAt");
		//v3.5.0版本提供`findObjectsByTable`方法查询自定义表名的数据
		type_info.findObjectsByTable(new QueryListener<JSONArray>() {
			@Override
			public void done(JSONArray ary, BmobException e) {
				try {
					if (e == null) {
						String str = ary.toString();
						GridViewAdapter adapter = new GridViewAdapter(getActivity(), JSON.parseArray(str, RecListBean.class));
						gridView.setAdapter(adapter);
					} else {
						ToastHelper.toast("当前网络不佳，请下拉刷新");
						showNetErro();
					}
				} catch (Exception e2) {
					ToastHelper.toast("当前网络不佳，请下拉刷新");
					showNetErro();
				}
			}
		});
	}

	public void formatList(List<ListConfig> listConfigs) {

		if (listConfigs == null || listConfigs.size() == 0)
			return;
		groups = new ArrayList<>();
		childs = new ArrayList<>();
		listId = new LinkedHashSet<>();

		for (ListConfig listConfig : listConfigs) {
			listId.add(listConfig.list_id);
		}
		Iterator<String> iterator = listId.iterator();
		List<ListConfig> temp;
		while (iterator.hasNext()) {
			String list_id = iterator.next();
			temp = new ArrayList<>();
			for (ListConfig listConfig : listConfigs) {

				if (list_id.equals(listConfig.list_id)) {
					if (temp.size() < 3)
						temp.add(listConfig);
				}
			}
			childs.add(temp);
		}
		for (List<ListConfig> child : childs) {
			if (child == null || child.size() == 0)
				continue;
			groups.add(child.get(0));
		}
	}

	public void  showNetErro(){
		llNetErro.setVisibility(View.VISIBLE);
		expendablelistview.setVisibility(View.GONE);
	}

	@OnClick(R.id.llNetErro)
	public void llNetErro(){
		initData();
	}
}
